//
//  RelationshipsViewController.m
//  ENTBoostChat
//
//  Created by zhong zf on 14-8-2.
//  Copyright (c) 2014年 EB. All rights reserved.
//

#import "RelationshipsViewController.h"
#import "ENTBoostChat.h"
#import "BDDynamicTree.h"
#import "BDDynamicTreeNode.h"
#import "ENTBoost.h"

#define EB_RELATIONSHIPS_VC_MY_DEPARTMENT_VIEW 200
#define EB_RELATIONSHIPS_VC_ENTERPRISE_VIEW 201
#define EB_RELATIONSHIPS_VC_PERSONALGROUP_VIEW 202
#define EB_RELATIONSHIPS_VC_CONTACT_VIEW 203

@interface RelationshipsViewController ()
{
    BDDynamicTree *_enterpriseDynamicTree; //企业组织架构
    BDDynamicTree *_personalGroupDynamicTree; //个人群组
    BDDynamicTree *_contactDynamicTree; //通讯录
    BDDynamicTree *_myDepartmentDynamicTree; //我的部门或讨论组
}
@end

@implementation RelationshipsViewController

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.relationshipArray = [NSMutableArray array];
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    CGRect rect = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 49);
    
    //我的部门和讨论组
    _myDepartmentDynamicTree = [[BDDynamicTree alloc] initWithFrame:rect nodes:[self myDepartmentNodes]];
    _myDepartmentDynamicTree.delegate = self;
    _myDepartmentDynamicTree.tag = EB_RELATIONSHIPS_VC_MY_DEPARTMENT_VIEW;
    
    //通讯录
    _contactDynamicTree = [[BDDynamicTree alloc] initWithFrame:rect nodes:[self contactNodes]];
    _contactDynamicTree.delegate = self;
    _contactDynamicTree.tag = EB_RELATIONSHIPS_VC_CONTACT_VIEW;
    
    //个人群组
    _personalGroupDynamicTree = [[BDDynamicTree alloc] initWithFrame:rect nodes:[self personalGroupNodes]];
    _personalGroupDynamicTree.delegate = self;
    _personalGroupDynamicTree.tag = EB_RELATIONSHIPS_VC_PERSONALGROUP_VIEW;
    
    //企业组织架构
    _enterpriseDynamicTree = [[BDDynamicTree alloc] initWithFrame:rect nodes:[self enterpriseGroupNodes]];
    _enterpriseDynamicTree.delegate = self;
    _enterpriseDynamicTree.tag = EB_RELATIONSHIPS_VC_ENTERPRISE_VIEW;
    
    //设置默认显示的视图
    [self.view addSubview:_myDepartmentDynamicTree];
    
    //生成切换视图的按钮
    UIBarButtonItem *contactButton = [[UIBarButtonItem alloc] initWithTitle:@"通讯录" style:UIBarButtonItemStylePlain target:self action:@selector(switchToContactView)];
    UIBarButtonItem *personalGroupButton = [[UIBarButtonItem alloc] initWithTitle:@"个人群组" style:UIBarButtonItemStylePlain target:self action:@selector(switchToPersonalGroupView)];
    UIBarButtonItem *enterpriseButton = [[UIBarButtonItem alloc] initWithTitle:@"企业架构" style:UIBarButtonItemStylePlain target:self action:@selector(switchToEnterpriseView)];
    UIBarButtonItem *myDepartmentButton = [[UIBarButtonItem alloc] initWithTitle:@"我的部门" style:UIBarButtonItemStylePlain target:self action:@selector(switchToMyDepartmentView)];
    
    self.navigationItem.leftBarButtonItems = @[myDepartmentButton, contactButton, personalGroupButton, enterpriseButton];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//移除指定视图
- (void)removeViewWithTag:(NSArray*)tags
{
    for (NSNumber *tagNumber in tags) {
        UIView* view = [self.view viewWithTag:tagNumber.integerValue];
        [view removeFromSuperview];
    }
}

//切换到企业架构视图
- (void)switchToEnterpriseView
{
    [self removeViewWithTag:@[@EB_RELATIONSHIPS_VC_PERSONALGROUP_VIEW, @EB_RELATIONSHIPS_VC_CONTACT_VIEW, @EB_RELATIONSHIPS_VC_MY_DEPARTMENT_VIEW]];
    [self.view addSubview:_enterpriseDynamicTree];
}

//切换到个人群组视图
- (void)switchToPersonalGroupView
{
    [self removeViewWithTag:@[@EB_RELATIONSHIPS_VC_ENTERPRISE_VIEW, @EB_RELATIONSHIPS_VC_CONTACT_VIEW, @EB_RELATIONSHIPS_VC_MY_DEPARTMENT_VIEW]];
    [self.view addSubview:_personalGroupDynamicTree];
}

//切换到通讯录视图
- (void)switchToContactView
{
    [self removeViewWithTag:@[@EB_RELATIONSHIPS_VC_ENTERPRISE_VIEW, @EB_RELATIONSHIPS_VC_PERSONALGROUP_VIEW, @EB_RELATIONSHIPS_VC_MY_DEPARTMENT_VIEW]];
    [self.view addSubview:_contactDynamicTree];
}

//切换到我的部门视图
- (void)switchToMyDepartmentView
{
    [self removeViewWithTag:@[@EB_RELATIONSHIPS_VC_ENTERPRISE_VIEW, @EB_RELATIONSHIPS_VC_PERSONALGROUP_VIEW, @EB_RELATIONSHIPS_VC_CONTACT_VIEW]];
    [self.view addSubview:_myDepartmentDynamicTree];
}

////填充部门或群组成员
//- (void)fillMembersForGroupInfos:(NSMutableArray*)targetArray myUid:(uint64_t)myUid
//{
//    for (BDDynamicTreeNode* node in [NSArray arrayWithArray:targetArray]) {
//        EBGroupInfo* groupInfo = node.data[@"groupInfo"];
//        
//        NSMutableArray* tmpMemberArry = [[NSMutableArray alloc] init];
//        BOOL isInGroup = NO;
//        for (id key in groupInfo.members) {
//            EBMemberInfo* memberInfo = groupInfo.members[key];
//            BDDynamicTreeNode* memberNode = [[BDDynamicTreeNode alloc] init];
//            memberNode.isDepartment = NO;
//            memberNode.parentNodeId = node.nodeId;
//            memberNode.nodeId = [NSString stringWithFormat:@"%llu", memberInfo.empCode];
//            memberNode.name = memberInfo.userName;
//            memberNode.isHiddenTalkBtn = YES;
//            memberNode.data = @{@"offset": [NSNumber numberWithInteger:memberInfo.offset], @"memberInfo": memberInfo, @"type": [NSNumber numberWithShort:RELATIONSHIP_TYPE_MEMBER]};
//            
//            if (memberInfo.uid == myUid)
//                isInGroup = YES;
//            
//            [tmpMemberArry addObject:memberNode];
//        }
//        
//        //如果当前用户存在于该部门或群组下，则显示点击对话按钮
//        if (isInGroup) {
//            node.isHiddenTalkBtn = NO;
//        }
//        
//        //成员排序
//        [tmpMemberArry sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//            NSNumber* offset1 = ((BDDynamicTreeNode* )obj1).data[@"offset"];
//            NSNumber* offset2 = ((BDDynamicTreeNode* )obj2).data[@"offset"];
//            return [offset1 compare:offset2];
//        }];
//        
//        [targetArray addObjectsFromArray:tmpMemberArry];
//    }
//
//}

/*把企业部门信息列表转换为树状视图数据源
 * @param groupInfos EBGroupInfo实例数组
 * @param type 联系人类型
 * @return BDDynamicTreeNode实例数组
 */
- (NSArray*)treeNodesDataWithGroupInfos:(NSDictionary*)groupInfos type:(RELATIONSHIP_TYPE)type
{
    NSMutableArray *tmpArry = [NSMutableArray array];
    [groupInfos enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        EBGroupInfo* groupInfo = obj;
        
        BDDynamicTreeNode* node = [[BDDynamicTreeNode alloc] init];
        node.isDepartment = YES;
        node.parentNodeId = groupInfo.parentCode?[NSString stringWithFormat:@"%llu", groupInfo.parentCode]:nil;
        node.nodeId = [NSString stringWithFormat:@"%llu", groupInfo.depCode];
        node.name = groupInfo.depName;
        if (groupInfo.type == EB_GROUP_TYPE_PROJECT) {
            node.name = [NSString stringWithFormat:@"%@[项目组]", groupInfo.depName];
        } else if (groupInfo.type == EB_GROUP_TYPE_TEMP) {
            node.name = [NSString stringWithFormat:@"%@[讨论组]", groupInfo.depName];
        }
        
        //如果当前用户存在于该部门下，则显示聊天按钮
        if (groupInfo.myEmpCode)
            node.isHiddenTalkBtn = NO;
        else
            node.isHiddenTalkBtn = YES;
        
        node.data = @{@"offset": @(groupInfo.offset), @"groupInfo": groupInfo, @"leafCount":@(groupInfo.memberCount), @"type": @(type)};
        
        [tmpArry addObject:node];
    }];
    
    //部门排序
    [tmpArry sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSNumber* offset1 = ((BDDynamicTreeNode* )obj1).data[@"offset"];
        NSNumber* offset2 = ((BDDynamicTreeNode* )obj2).data[@"offset"];
        return [offset1 compare:offset2];
    }];
    
//    //填充部门成员数据
//    [self fillMembersForGroupInfos:tmpArry myUid:[ENTBoostKit sharedToolKit].accountInfo.uid];
    
    return [NSArray arrayWithArray:tmpArry];
}

/**获取我的部门和讨论组信息
 * @return BDDynamicTreeNode实例数组
 */
- (NSArray *)myDepartmentNodes
{
    ENTBoostKit* ebKit = [ENTBoostKit sharedToolKit];
    
    //遍历所有部门，寻找当前用户所属的部门
//    uint64_t myUid = ebKit.accountInfo.uid;
    NSMutableArray* tmpArry = [[NSMutableArray alloc] init];
    [ebKit.entGroupInfos enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        EBGroupInfo* groupInfo = obj;
        
        if (groupInfo.myEmpCode) { //如果当前用户存在于该部门中
            BDDynamicTreeNode* node = [[BDDynamicTreeNode alloc] init];
            node.isDepartment = YES;
            node.parentNodeId = nil;
            node.nodeId = [NSString stringWithFormat:@"%llu", groupInfo.depCode];
            node.name = groupInfo.depName;
            if (groupInfo.type == EB_GROUP_TYPE_PROJECT) {
                node.name = [NSString stringWithFormat:@"%@[项目组]", groupInfo.depName];
            } else if (groupInfo.type == EB_GROUP_TYPE_TEMP) {
                node.name = [NSString stringWithFormat:@"%@[讨论组]", groupInfo.depName];
            }
            
            //如果当前用户存在于该部门下，则显示聊天按钮
            if (groupInfo.myEmpCode)
                node.isHiddenTalkBtn = NO;
            else
                node.isHiddenTalkBtn = YES;
            
            node.data = @{@"offset": @(groupInfo.offset), @"groupInfo": groupInfo, @"leafCount":@(groupInfo.memberCount), @"type": @(RELATIONSHIP_TYPE_MYDEPARTMENT)};
            
            [tmpArry addObject:node];
            
//            [ebKit loadMemberInfosWithDepCode:groupInfo.depCode onCompletion:^(NSArray *memberInfos) {
////                EBGroupInfo* groupInfo = [ebKit groupInfoWithDepCode:memberInfo.depCode];
////                if (!groupInfo)
////                    return;
//                
////                if (groupInfo.type == EB_GROUP_TYPE_TEMP)
////                    return;
//                
//
//            } onFailure:^(NSError *error) {
//                
//            }];
            
        }
        
//        EBMemberInfo* memberInfo = obj;
        
//        if (memberInfo.uid && memberInfo.uid == myUid) {
//
//        }
    }];
    
    //排序
    [tmpArry sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSNumber* offset1 = ((BDDynamicTreeNode* )obj1).data[@"offset"];
        NSNumber* offset2 = ((BDDynamicTreeNode* )obj2).data[@"offset"];
        return [offset1 compare:offset2];
    }];

//    //填充部门成员数据
//    [self fillMembersForGroupInfos:tmpArry myUid:myUid];
    
    return [NSArray arrayWithArray:tmpArry];
}

/**获取所有企业部门信息
 * @return BDDynamicTreeNode实例数组
 */
- (NSArray *)enterpriseGroupNodes
{
    return [self treeNodesDataWithGroupInfos:[ENTBoostKit sharedToolKit].entGroupInfos type:RELATIONSHIP_TYPE_ENTGROUP];
}

/**获取所有个人群组信息
 * @return BDDynamicTreeNode实例数组
 */
- (NSArray *)personalGroupNodes
{
    return [self treeNodesDataWithGroupInfos:[ENTBoostKit sharedToolKit].personalGroupInfos type:RELATIONSHIP_TYPE_PERSONALGROUP];
}

/**获取通讯录信息
 * @return BDDynamicTreeNode实例数组
 */
- (NSArray *)contactNodes
{
    NSMutableArray *arry = [NSMutableArray array];
    
    //获取通讯录分组
    NSMutableDictionary* groupNames = [[NSMutableDictionary alloc] init];
    NSDictionary* contactInfos = [ENTBoostKit sharedToolKit].contactInfos;
    [contactInfos enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        EBContactInfo* contactInfo = obj;
        if (contactInfo.groupName)
            groupNames[contactInfo.groupName] = contactInfo.groupName;
    }];
    
    [groupNames enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        BDDynamicTreeNode* node = [[BDDynamicTreeNode alloc] init];
        node.isDepartment = YES;
        node.parentNodeId = nil;
        node.nodeId = obj;
        node.name = obj;
        node.isHiddenTalkBtn = YES;
        
        [arry addObject:node];
    }];
    
    //获取通讯录中联系人
    NSMutableArray* tmpContactArry = [[NSMutableArray alloc] init];
    [contactInfos enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        EBContactInfo* contactInfo = obj;
        BDDynamicTreeNode* node = [[BDDynamicTreeNode alloc] init];
        node.isDepartment = NO;
        node.parentNodeId = contactInfo.groupName?contactInfo.groupName:nil;
        node.nodeId = contactInfo.contact;
        node.name = contactInfo.name?contactInfo.name:contactInfo.contact;
        node.isHiddenTalkBtn = YES;
        node.data = @{@"offset": [NSNumber numberWithInteger:contactInfo.offset], @"contactInfo": contactInfo, @"type": [NSNumber numberWithShort:RELATIONSHIP_TYPE_CONTACT]};
        
        [tmpContactArry addObject:node];
    }];
    
    //排序
    [tmpContactArry sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSNumber* offset1 = ((BDDynamicTreeNode* )obj1).data[@"offset"];
        NSNumber* offset2 = ((BDDynamicTreeNode* )obj2).data[@"offset"];
        return [offset1 compare:offset2];
    }];
    
    [arry addObjectsFromArray:tmpContactArry];
    
    return [NSArray arrayWithArray:arry];
}

#pragma mark - BDDynamicTreeDelegate
- (void)dynamicTree:(BDDynamicTree *)dynamicTree didSelectedRowWithNode:(BDDynamicTreeNode *)node
{
    [[NSNotificationCenter defaultCenter] postNotificationName:EBCHAT_NOTIFICATION_RELATIONSHIP_DIDSELECT object:self userInfo:@{@"node": node}];
}

- (void)dynamicTree:(BDDynamicTree *)dynamicTree talkBtnTapInNode:(BDDynamicTreeNode *)node
{
    [[NSNotificationCenter defaultCenter] postNotificationName:EBCHAT_NOTIFICATION_RELATIONSHIP_DIDSELECT object:self userInfo:@{@"node": node}];
}

- (void)dynamicTree:(BDDynamicTree *)dynamicTree loadLeafUnderNode:(BDDynamicTreeNode *)parentNode onCompletion:(void(^)(NSArray *))completionBlock
{
    EBGroupInfo* groupInfo = parentNode.data[@"groupInfo"];
    [[ENTBoostKit sharedToolKit] loadMemberInfosWithDepCode:groupInfo.depCode onCompletion:^(NSArray *memberInfos) {
        if (completionBlock) {
            NSMutableArray* tmpMemberNodes = [[NSMutableArray alloc] init];
            for (EBMemberInfo* memberInfo in memberInfos) {
                BDDynamicTreeNode* memberNode = [[BDDynamicTreeNode alloc] init];
                memberNode.isDepartment = NO;
                memberNode.parentNodeId = parentNode.nodeId;
                memberNode.nodeId = [NSString stringWithFormat:@"%llu", memberInfo.empCode];
                memberNode.name = memberInfo.userName;
                memberNode.isHiddenTalkBtn = YES;
                memberNode.data = @{@"offset": [NSNumber numberWithInteger:memberInfo.offset], @"memberInfo": memberInfo, @"type": [NSNumber numberWithShort:RELATIONSHIP_TYPE_MEMBER]};

                [tmpMemberNodes addObject:memberNode];
            }

            //成员排序
            [tmpMemberNodes sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                NSNumber* offset1 = ((BDDynamicTreeNode* )obj1).data[@"offset"];
                NSNumber* offset2 = ((BDDynamicTreeNode* )obj2).data[@"offset"];
                return [offset1 compare:offset2];
            }];

            completionBlock([NSArray arrayWithArray:tmpMemberNodes]);
        }
    } onFailure:^(NSError *error) {
        NSLog(@"加载成员信息失败, code = %i, msg = %@", error.code, error.localizedDescription);
    }];
}

@end
